package thread;

import servlet.HttpServlet;
import servlet.Servlet;
import sevletpojo.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @author 王瑞
 * @description:
 * @date 2020/3/2  13:45
 */
public class ConditionThread extends Thread {

    private Socket socket;

    //private Map<String, HttpServlet> servletMap;

    private List<Mapper> mapperList ;




    public ConditionThread(Socket socket, List<Mapper> mapperList){
        this.socket = socket;
        this.mapperList = mapperList;
    }


    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);
            //localhost:8080/demo2/lagou
            // /demo2/lagou
            HttpServlet servlet = null;
            String urlName = request.getUrl();
            String[] split = urlName.split("/");
            String s = split[1];
            String s1 = split[2];

            for (Mapper mapper : mapperList) {
                List<Host> hostList = mapper.getHostList();
                for (Host host : hostList) {
                    for (Context context : host.getContextList()) {
                        String name = context.getName();
                        if (name.equals(s)){
                            List<Wrapper> wrapperList = context.getWrapperList();
                            for (Wrapper wrapper : wrapperList) {
                                String wrapperName = wrapper.getName();
                                if (wrapperName.equals("/"+s1)){
                                    servlet = (HttpServlet) wrapper.getServlet();
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (servlet == null) {
                response.outPutHtml(request.getUrl());
            } else {
                servlet.service(request, response);
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
